import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 科室信息类型定义
 */
export interface Dept {
  id: number
  deptCode: string
  deptName: string
  parentId?: number
  hospitalId: number
  delFlag: 'Y' | 'N'
  createTime: string
  updateTime: string
}

/**
 * 科室查询参数
 */
export interface DeptSearchParams extends PageParams {
  deptName?: string
  deptCode?: string
  hospitalId?: number
  delFlag?: 'Y' | 'N'
}

/**
 * 获取科室列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchDepts = async (params: DeptSearchParams): Promise<PageResult<Dept>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<Dept>>>('/api/depts', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取科室列表失败')
    throw error
  }
}

/**
 * 获取科室详情
 * @param id 科室ID
 * @returns 科室详情
 */
export const getDept = async (id: number): Promise<Dept> => {
  try {
    const { data } = await request.get<BaseResponse<Dept>>(`/api/depts/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取科室详情失败')
    throw error
  }
}

/**
 * 创建科室
 * @param data 科室数据
 * @returns 创建的科室信息
 */
export const createDept = async (data: Omit<Dept, 'id'>): Promise<Dept> => {
  try {
    const { data: response } = await request.post<BaseResponse<Dept>>('/api/depts', data)
    ElMessage.success('创建科室成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建科室失败')
    throw error
  }
}

/**
 * 更新科室
 * @param data 科室数据
 * @returns 更新后的科室信息
 */
export const updateDept = async (data: Dept): Promise<Dept> => {
  try {
    const { data: response } = await request.put<BaseResponse<Dept>>(`/api/depts/${data.id}`, data)
    ElMessage.success('更新科室成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新科室失败')
    throw error
  }
}

/**
 * 删除科室
 * @param id 科室ID
 */
export const deleteDept = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/depts/${id}`)
    ElMessage.success('删除科室成功')
  } catch (error) {
    ElMessage.error('删除科室失败')
    throw error
  }
}

/**
 * 切换科室状态
 * @param id 科室ID
 * @param delFlag 状态标记
 */
export const toggleDeptStatus = async (id: number, delFlag: 'Y' | 'N'): Promise<void> => {
  try {
    await request.patch(`/api/depts/${id}/status`, { delFlag })
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    throw error
  }
}

// 缓存最近请求的科室数据
const deptCache = new Map<number, Dept>()

/**
 * 获取科室详情（带缓存）
 * @param id 科室ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 科室详情
 */
export const getDeptWithCache = async (id: number, forceRefresh = false): Promise<Dept> => {
  if (!forceRefresh && deptCache.has(id)) {
    return deptCache.get(id)!
  }

  const dept = await getDept(id)
  deptCache.set(id, dept)
  return dept
}
